package universe;

import java.util.Observable;


public class Game extends Observable implements Runnable{

	private 	Board 	board;
	private 	int 	score;
	private 	boolean	pause;
	private		BlockHandler	currentBlock;
	private		Block	nextBlock;
	private boolean gameOver;

	//il faut tester les déplacer sur les cotes avec non franchissement des bords

	public Game(){
		board	= new Board(Utils.BOARD_WIDTH, Utils.BOARD_HEIGHT);
		score	= 0;
		pause 	= false;

		gameOver = false;
		nextBlock	=	Block.getRandomBlock(); 
		currentBlock =	new BlockHandler(this.getNextBlock(), this.getBoard());
	}

	//Actions utilisateur
	public void run()
	{
		System.out.println("debut du game.run()");
		// boucle tant que la durée de vie du Thread est < à 5 secondes
		while(!gameOver) {
			// traitement
			if(!pause){								
				if(!currentBlock.goDown())
				{
					board.pushBlock(currentBlock.getB(), currentBlock.getX(), currentBlock.getY());
					nextBlock	=	Block.getRandomBlock(); 
					currentBlock =	new BlockHandler(this.getNextBlock(), this.getBoard());
					
					if(!(board.pushAllowed(currentBlock.getB(), currentBlock.getX(), currentBlock.getY())))
					{
						gameOver = true;
					}
					

				}
				
				this.setChanged();
				this.notifyObservers();
				//System.out.println("position X"+currentBlock.getX()+"position y"+currentBlock.getY());
			}	
			try {
				// pause
				Thread.sleep(Utils.TIMER_MS);
			}
			catch (InterruptedException ex) {}		
		}
		System.out.println("fini");


		//System.out.println(board.toString());

	}


	


	public void moveRight(){
		if(!pause || !gameOver){
			currentBlock.goRight();
			this.setChanged();
			this.notifyObservers();
		}
	}

	public void moveLeft(){
		if(!pause || !gameOver){
			currentBlock.goLeft();
			this.setChanged();
			this.notifyObservers();
		}
	}

	public void moveDown(){
		if(!pause || !gameOver){
			currentBlock.goDown();
			this.setChanged();
			this.notifyObservers();
		}
	}

	public void rotate(){
		if(!pause || !gameOver){
			currentBlock.rotate();
			this.setChanged();
			this.notifyObservers();
		}
	}

	// Getters and Setters

	public Board getBoard() {
		return board;
	}



	public void setBoard(Board board) {
		this.board = board;
	}



	public int getScore() {
		return score;
	}



	public void setScore(int score) {
		this.score = score;
	}



	public boolean getPause() {
		return pause;
	}

	public void togglePause() {
		this.pause = !this.pause;
	}



	public BlockHandler getCurrentBlock() {
		return currentBlock;
	}



	public void setCurrentBlock(BlockHandler currentBlock) {
		this.currentBlock = currentBlock;
	}



	public Block getNextBlock() {
		return nextBlock;
	}



	public void setNextBlock(Block nextBlock) {
		this.nextBlock = nextBlock;
	}

}

